# -*- coding: utf-8 -*-
# Copyright © 2017 Beijing HengXingChangDa Technology Co., Ltd. All rights reserved.

from utils.reqres import *
import requests
from cows.config import *
from user.models import CSMUser
from user.user import user_login
from evaluation.models import Evaluation
from proto.csm import *

import re
zh_pattern = re.compile(u'[\u4e00-\u9fa5]+')
def contain_zh(word):
      word = word.encode("utf-8").decode("utf-8")
      global zh_pattern
      match = zh_pattern.search(word)
      return match


class Ticket:
    def __init__(self):
        self.status = None
        self.category = None
        self.mdrid = None
        self.mpiid = None
        self.mpid = None
        self.desc = None
        self.username = None
        self.detail = None
        self.Impact = None
        self.Urgency = None
        self.Priority = None
        self.AssignedCaseID = None
        self.AssignedID = None
        self.Phase = None
        self.lastupdate = None
        self.score = None
        self.StatusDetail = None

    def to_dict(self, detail=False):
        d = dict()
        if contain_zh(self.status):
            if self.status == u"新建":
                d['status'] = "New"
            elif self.status == u"已解决":
                d['status'] = "Resolved"
            elif self.status == u"已关闭":
                d['status'] = "Closed"
            else:
                d['status'] = "Active"
        else:
            d['status'] = self.status

        d['category'] = self.category
        d['mdrid'] = self.mdrid
        d['mpiid'] = self.mpiid
        d['mpid'] = self.mpid
        d['AssignedCaseID'] = self.AssignedCaseID
        d['AssignedID'] = self.AssignedID
        d['desc'] = self.desc
        d['Phase'] = self.Phase
        d['lastupdate'] = self.lastupdate
        if detail:
            d['username'] = self.username
            d['detail'] = self.detail
            d['Impact'] = self.Impact
            d['Urgency'] = self.Urgency
            d['Priority'] = self.Priority
            d['score'] = self.score
            d['StatusDetail'] = self.StatusDetail
        return d


def handle_list(req):
    req = get_request(req, 'GET')
    if 'token' not in req:
        return BadRequest()

    type = req.get('type', 'pending')
    if type == 'pending':
        status = " and (NonTranslatedTicketStatus eq 'New')"
    elif type == 'serving':
        status = " and (NonTranslatedTicketStatus eq 'Active' or NonTranslatedTicketStatus eq 'Queued' or NonTranslatedTicketStatus eq 'Submitted' or NonTranslatedTicketStatus eq 'Escalated' or NonTranslatedTicketStatus eq 'Completed' or NonTranslatedTicketStatus eq 'Approved' or NonTranslatedTicketStatus eq 'Pending')"
    elif type == 'rating':
        status = " and (NonTranslatedTicketStatus eq 'Closed' or NonTranslatedTicketStatus eq 'Resolved')"
    elif type == 'complete':
        status = " and (NonTranslatedTicketStatus eq 'Closed' or NonTranslatedTicketStatus eq 'Resolved')"
    else:
        status = ""

    qs = CSMUser.get_all().filter(token=req['token'])
    if not qs:
        user = user_login()
    else:
        user = qs[0]
    user = qs[0]
    sid = user.csm_slice_id
    uid = user.csm_user_id
    # $filter=((NonTranslatedTicketStatus ne 'Archive' and NonTranslatedTicketStatus ne 'Request - Delete' and NonTranslatedTicketStatus ne 'Closed') and (OrgStatus eq 0))&
    # INClause=AssignedGroupID~~-1,34,31,30,11,2,1&
    # $select=AssignedCaseID,AssignedID,TypeName,Priority,SLAResolveByTimestamp,SLAComplianceStatus,TranslatedTypeName,TranslatedSLAComplianceStatus,CreationTimestamp,LastModTimestamp,Description,RequesterVIPFlag,RequesterUserName,RequesterOrgName,RequestedForUserName,RequestedForOrgName,RequesterOrgHierarchicalPath,RequesterRootOrgName,TicketStatus,ReasonCode,AssignedIndividual,AssignedGroup,MdrElementID,LockedByExternalUserId,CategorizationClass,CategorizationCategory,CategorizationType,CategorizationItem,HasAttachments&
    # categorytype=list&
    # CTGREQUEST=TRUE&
    # _dc=1504059926934&
    # $format=json&$skip=0&$top=25&
    # $orderby=LastModTimestamp desc&
    # $inlinecount=allpages
    url = '{server}/NimsoftServiceDesk/{sid}/servicedesk/odata/Ticket'.format(server=CSM_SERVER, sid=sid)
    params = list()
    params.append(('$filter', "((RequesterExternalUserID eq '{uid}' or RequestedForExternalUserID eq '{uid}') {status})".format(uid=uid, status=status)))
    params.append(('$select', 'Priority,TranslatedTypeName,RequesterUserName,TypeName,Description,TicketIdentifier,TicketStatus,Phase,AssignedCaseID,AssignedID,LastModTimestamp'))
    params.append(('$orderby', 'LastModTimestamp desc'))
    params.append(('$format', 'json'))
    params.append(('$skip', '0'))
    params.append(('$top', '10000'))
    # params.append(('CTGREQUEST', 'TRUE'))
    # params.append(('_dc', '1504059926934'))
    # params.append(('INClause', 'AssignedGroupID~~-1,34,31,30,11,2,1'))
    params.append(('$inlinecount', 'allpages'))

    retried = False
    while True:
        cookies = user.getCookie()
        res = requests.get(url, params=tuple(params), cookies=cookies)
        if retried:
            break
        if res.status_code == requests.codes.unauthorized:
            user = user_login(user.username, user.password)
            retried = True
            continue
        break

    tickets = list()
    if res.status_code == requests.codes.ok:
        csmres = res.json()
        # return response_json(csmres)
        for csmt in csmres['d']['results']:
            t = Ticket()
            t.Priority = csmt['Priority']
            t.desc = csmt['Description']
            t.category = csmt['TranslatedTypeName']
            t.status = csmt['TicketStatus']
            t.mdrid = csmt['MdrElementID']
            t.mpiid = csmt['MdrProdInstance']
            t.mpid = csmt['MdrProduct']
            t.username = csmt['RequesterUserName']
            t.lastupdate = csmt['LastModTimestamp']
            t.AssignedCaseID = csmt['AssignedCaseID']
            t.AssignedID = csmt['AssignedID']
            t.Phase = csmt.get('Phase', '0')
            if type == 'complete' or type == 'rating':
                qs = Evaluation.get_all().filter(token=user.token, mdrid=t.mdrid, mpiid=t.mpiid, mpid=t.mpid)
                if qs:
                    if type == 'rating':
                        continue
                else:
                    if type == 'complete':
                        continue
                    t.status = 'Rating'
            tickets.append(t)
    else:
        # print res.url
        # print res.status_code
        res.raise_for_status()

    return handle_result(Ticket, req, tickets, detail=False)



def handle_info(req):
    req = get_request(req, 'GET')
    if 'token' not in req \
            or 'mdrid' not in req \
            or 'mpiid' not in req \
            or 'mpid' not in req:
        return BadRequest()

    qs = CSMUser.get_all().filter(token=req['token'])
    if not qs:
        user = user_login()
    else:
        user = qs[0]
    user = qs[0]
    sid = user.csm_slice_id

    MdrElementID = req.get('mdrid', '207')
    MdrProdInstance = req.get('mpiid', '1100001')
    MdrProduct = req.get('mpid', 'CA:00050')
    csmt = csm_ticket_info(user, MdrElementID, MdrProdInstance, MdrProduct)
    t = Ticket()
    t.Priority = csmt['Priority']
    t.Impact = csmt['Impact']
    t.Urgency = csmt['Urgency']
    t.desc = csmt['Description']
    t.category = csmt['TranslatedTypeName']
    t.status = csmt['TicketStatus']
    t.mdrid = csmt['MdrElementID']
    t.mpiid = csmt['MdrProdInstance']
    t.mpid = csmt['MdrProduct']
    t.detail = csmt['DescriptionLong']
    t.username = csmt['RequesterUserName']
    t.lastupdate = csmt['LastModTimestamp']
    t.AssignedCaseID = csmt['AssignedCaseID']
    t.AssignedID = csmt['AssignedID']
    CustemField = csmt.get('HasCustomFieldMetadata', None)
    if CustemField:
        t.StatusDetail = CustemField['results'][1]['AttributeValue']
        if t.StatusDetail != "":
            dd = json.loads(t.StatusDetail)
            t.StatusDetail = dd
    t.Phase = csmt.get('Phase', '0')
    if t.status == 'Closed' or t.status == 'Resolved':
        qs = Evaluation.get_all().filter(token=user.token, mdrid=t.mdrid, mpiid=t.mpiid, mpid=t.mpid)
        if not qs:
            t.status = 'Rating'
        else:
            e = qs[0]
            t.score = e.score

    return response_json(t.to_dict(True))


def handle_set(req):
    return NotFound()


def handle_add(req):
    d = json.loads(req.body)
    req = get_request(req, 'POST')
    req.update(d)

    if 'token' not in req \
            or 'desc' not in req \
            or 'detail' not in req:
        return BadRequest()

    qs = CSMUser.get_all().filter(token=req['token'])
    if not qs:
        user = user_login()
    else:
        user = qs[0]
    sid = user.csm_slice_id
    uid = user.csm_user_id

    url = "{server}/NimsoftServiceDesk/{sid}/servicedesk/odata/ServiceRequest".format(server=CSM_SERVER, sid=sid)
    params = list()
    # params.append(('$orderby', 'LastModTimestamp desc'))
    params.append(('$format', 'json'))
    # params.append(('categorytype', 'list'))
    # params.append(('expand_top', ''))
    # params.append(('$expand', 'HasCustomFieldMetadata,HasAutomatedFulfillmentDetails'))
    # params.append(('orderby', 'HasTicket/LastModTimestamp desc,IsConnectedTo/CreationTimestamp desc'))
    # params.append(('_dc', '1504594430881'))
    headers = dict()
    headers['Content-Type'] = 'application/json'
    headers['Accept'] = 'application/json, application/json'

    ticket = dict()
    ticket['Description'] = req.get('desc', "")
    ticket['DescriptionLong'] = req.get("detail", '')
    ticket['Impact'] = req.get("Impact", 'Low')
    ticket['Urgency'] = req.get("Urgency", 'Low')
    ticket['Priority'] = req.get("Priority", 'Low')
    # t['RequesterUserName'] = user.username
    ticket['RequesterAltEmail'] = user.email

    data = json.dumps(ticket)

    retried = False
    while True:
        cookies = user.getCookie()
        res = requests.post(url, params=tuple(params), cookies=cookies, headers=headers, data=data)
        if retried:
            break
        if res.status_code == requests.codes.unauthorized:
            user = user_login(user.username, user.password)
            retried = True
            continue
        break
    if res.status_code == requests.codes.created:
        csmres = res.json()
        csmt = csmres['d']
        t = Ticket()
        t.Priority = csmt['Priority']
        t.Impact = csmt['Impact']
        t.Urgency = csmt['Urgency']
        t.desc = csmt['Description']
        t.category = csmt['TranslatedTypeName']
        t.status = csmt['ReasonCode']
        t.status = csmt['TicketStatus']
        t.mdrid = csmt['MdrElementID']
        t.mpiid = csmt['MdrProdInstance']
        t.mpid = csmt['MdrProduct']
        t.detail = csmt['DescriptionLong']
        t.username = csmt['RequesterUserName']
        t.lastupdate = csmt['LastModTimestamp']
        t.AssignedCaseID = csmt['AssignedCaseID']
        t.AssignedID = csmt['AssignedID']
    else:
        # print res.url
        # print res.text
        # print res.status_code
        res.raise_for_status()

    return response_json(t.to_dict(True))


def handle_del(req):
    return NotFound()


def handle_echo(req):
    #req = get_request(req, 'GET')
    return HttpResponse(req.body)


